package com.sxm.yiwei.activitis;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sxm.yiwei.MainActivity;
import com.sxm.yiwei.R;
import com.sxm.yiwei.tools.ErrType;
import com.sxm.yiwei.tools.IsLogin;
import com.sxm.yiwei.utils.InternetAddressUtis;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

public class MineInstall extends BaseActivity implements View.OnClickListener{
    private Button colse;
    private Button open;
    private Button useropen;
    private SharedPreferences sharedPreferences;
    private String appId;
    private String userId;
    private String token;
    private String isNotify;
    private int i;//返回码
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    // 刷新以后结束
                   startActivity(new Intent(MineInstall.this, MainActivity.class));
                    finish();

                break;
            }
        }
    };
    private ImageView installback;
    private Switch aSwitch;
    private ImageView backmain;


    // 刷新数据
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mine_install);
        initInstallView();
        sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        appId = sharedPreferences.getString("appid", "");
        userId = sharedPreferences.getString("userId", "");
        token = sharedPreferences.getString("token", "");

        getPush();


    }

    @Override
    protected void onRestart() {
        super.onRestart();
        sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        appId = sharedPreferences.getString("appid", "");
        userId = sharedPreferences.getString("userId", "");
        token = sharedPreferences.getString("token", "");
        getPush();

    }

    private void initInstallView() {
        backmain = (ImageView) findViewById(R.id.mineinstall_backmain);
        useropen = (Button) findViewById(R.id.install_useropen);
        installback = (ImageView) findViewById(R.id.mine_install_back);
        aSwitch = (Switch) findViewById(R.id.switch_bt);
        installback.setOnClickListener(this);
        useropen.setOnClickListener(this);
        backmain.setOnClickListener(this);
        aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
               if (isChecked){
                   isNotiy = 1;
                   if (i==isNotiy){
                   }else{
                       setPush();
                   }
               }else {
                   isNotiy = 0;
                   if (i==isNotiy){
                   }else{
                       setPush();
                   }
               }
            }
        });
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.mineinstall_backmain:
                startActivity(new Intent(MineInstall.this,MainActivity.class));
                AppManager.getAppManager().finishAllActivity();
                break;
            case R.id.mine_install_back:
                finish();
                break;
            case R.id.install_useropen:// 推出登陆
                AlertDialog.Builder builder = new AlertDialog.Builder(MineInstall.this);
                View view = LayoutInflater.from(MineInstall.this).inflate(R.layout.cancel_servicedialog, null);
                TextView t2 = (TextView) view.findViewById(R.id.cancel_t2);
                Button surebt = (Button) view.findViewById(R.id.cancel_surebt);
                Button cancelbt = (Button) view.findViewById(R.id.cancel_cancelbt);
                builder.setView(view);
                t2.setText("退出当前登陆账号");
                final AlertDialog dialog = builder.create();
                surebt.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        userOpen();
                        dialog.dismiss();
                    }
                });
                cancelbt.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                dialog.show();
                break;

        }
    }

    private int  isNotiy = 0;

    // 设置推送状态
    private void setPush() {

        RequestParams params = new RequestParams(InternetAddressUtis.Url+"/user/setNotify");
        params.addHeader("Content-Type","application/json");
        params.addHeader("token",token);
        params.addHeader("appId",appId);
        params.addHeader("userId",userId);
        JSONObject json = new JSONObject();
        json.put("isNotify",isNotiy+"");
        params.setBodyContent(json.toJSONString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Toast.makeText(MineInstall.this, "设置成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ErrType.errType(MineInstall.this,ex);
            }
            @Override
            public void onCancelled(CancelledException cex) {
            }
            @Override
            public void onFinished() {

            }
        });
    }
    //获取当前的推送状态
    private void getPush(){
        if (token.equals("")){
            // 用户只能在登陆状态下才能设置消息推送状态
            IsLogin.isLogin();
        }else {
            RequestParams params = new RequestParams(InternetAddressUtis.Url+"/user/isNotify");
            params.addHeader("Content-Type","application/json");
            params.addHeader("token",token);
            params.addHeader("appId",appId);
            params.addHeader("userId",userId);

            x.http().get(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    com.alibaba.fastjson.JSONObject obj = JSON.parseObject(result);
                    String data = obj.getString("data");
                    com.alibaba.fastjson.JSONObject obj1 = JSON.parseObject(data);
                    isNotify = obj1.getString("isNotify");
                    i = Integer.parseInt(isNotify);
                    SharedPreferences.Editor edit = sharedPreferences.edit();
                    edit.putString("isNotify",isNotify);
                    edit.commit();
                    if (i==1){
                        aSwitch.setChecked(true);
                    }else {
                        aSwitch.setChecked(false);
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                    ErrType.errType(MineInstall.this,ex);
                }
                @Override
                public void onCancelled(CancelledException cex) {
                }
                @Override
                public void onFinished() {

                }
            });
        }

    }
        // 退出登陆
    private void userOpen() {
        RequestParams p = new RequestParams(InternetAddressUtis.Url+"/user/exit");
        p.addHeader("Content-Type","application/json");
        p.addHeader("token",token);
        p.addHeader("appId",appId);
        p.addHeader("userId",userId);
        x.http().post(p, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                SharedPreferences.Editor edit = sharedPreferences.edit();
                edit.putString("token","");
                edit.putString("userId","");

                edit.commit();
                AlertDialog.Builder builder = new AlertDialog.Builder(MineInstall.this);
                View view = LayoutInflater.from(MineInstall.this).inflate(R.layout.cancel_servicedialog, null);
                TextView t2 = (TextView) view.findViewById(R.id.cancel_t2);
                Button surebt = (Button) view.findViewById(R.id.cancel_surebt);
                Button cancelbt = (Button) view.findViewById(R.id.cancel_cancelbt);
                builder.setView(view);
                t2.setText("退出登陆成功");
                final AlertDialog dialog = builder.create();
                surebt.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        handler.sendEmptyMessage(1);
                        dialog.dismiss();
                    }
                });
                cancelbt.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                dialog.show();


            }


            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("tag", "onError: 设置退出登录--");
                ErrType.errType(MineInstall.this,ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
}
